package cycles.util.jdbc;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;

import cycles.util.jdbc.SampleBean;
import cycles.util.jdbc.TableMapper;

public class SampleService {

	TableMapper<SampleBean> dao;

	Map<Integer,Field[]> updates;
	
	Field nickfld;
	int sqlid_update_ilist;
	public void setJdbcTemplate(JdbcTemplate jt) {
		dao = new TableMapper<SampleBean>(jt, SampleBean.class, "sample_table");
		
		//这里可以做一些预制准备，比如准备频繁进行的操作，最好把相应的的field做cache
		updates = new HashMap<Integer,Field[]>();
		Field ilist=null ;
		try {
			ilist = SampleBean.class.getDeclaredField("intlist");
			nickfld = SampleBean.class.getDeclaredField("nick");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		sqlid_update_ilist= dao.addUpdate(new Field[]{ilist});
	}
	
	int updateName(SampleBean sb){
		return dao.update(sb, nickfld);
	}
	int updateIList(SampleBean sb){
		return dao.updates(this.sqlid_update_ilist, new Object[]{sb.intlist,sb.id});
	}
	SampleBean get(int id) {
		return dao.select(id);
	}

	boolean del(int id) {
		return dao.delete(id) > 0;
	}

	SampleBean add() {
		SampleBean sb = new SampleBean();
		sb.id = -1;// -1 means not in db yet
		sb.intlist = new int[] { 1, 2, 3, 4, 5 };
		sb.spec = "not in db";
		sb.nick = "new entry";
		if(dao.insert(sb)){
			return sb;
		}else {
			return null;
		}
		
	}

}
